const { app, BrowserWindow, ipcMain, globalShortcut, screen } = require('electron');
const path = require('path');
const Store = require('electron-store');
const config = require('../config.local.js');
const apiConfig = require('../api.config.js');

// 创建配置存储
const store = new Store();

let mainWindow;
let isQuitting = false;

function createWindow() {
  // 获取屏幕尺寸
  const { width, height } = screen.getPrimaryDisplay().workAreaSize;
  
  // 创建浏览器窗口
  mainWindow = new BrowserWindow({
    width: 400,
    height: 80,
    x: store.get('windowPosition.x', Math.floor((width - 400) / 2)),
    y: store.get('windowPosition.y', height - 200),
    frame: false, // 无边框
    transparent: true, // 透明背景
    alwaysOnTop: true, // 始终置顶
    skipTaskbar: true, // 不显示在任务栏
    resizable: false, // 不可调整大小
    movable: true, // 可移动
    minimizable: false,
    maximizable: false,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true
    }
  });

  // 加载应用的 index.html
  mainWindow.loadFile('src/renderer/index.html');

  // 窗口准备就绪时显示
  mainWindow.once('ready-to-show', () => {
    mainWindow.show();
    
    // 开发者工具默认关闭
    // if (process.argv.includes('--dev')) {
    //   mainWindow.webContents.openDevTools();
    // }
    
    // 设置窗口位置到屏幕底部居中
    const { screen } = require('electron');
    const primaryDisplay = screen.getPrimaryDisplay();
    const { width: screenWidth, height: screenHeight } = primaryDisplay.workAreaSize;
    
    const windowBounds = mainWindow.getBounds();
    const x = Math.round((screenWidth - windowBounds.width) / 2);
    const y = screenHeight - windowBounds.height - 50; // 距离底部50px
    
    mainWindow.setPosition(x, y);
  });

  // 窗口关闭时的处理
  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  // 保存窗口位置
  mainWindow.on('moved', () => {
    const position = mainWindow.getPosition();
    store.set('windowPosition', { x: position[0], y: position[1] });
  });

  // 防止窗口被意外关闭
  mainWindow.on('close', (event) => {
    if (!isQuitting) {
      event.preventDefault();
      mainWindow.hide();
    }
  });

  // 设置窗口图标（如果有的话）
  // mainWindow.setIcon(path.join(__dirname, '../assets/icon.png'));
}

// 当 Electron 完成初始化并准备创建浏览器窗口时调用此方法
app.whenReady().then(() => {
  createWindow();

  // 注册全局快捷键显示/隐藏窗口
  globalShortcut.register('Alt+Space', () => {
    if (mainWindow) {
      if (mainWindow.isVisible()) {
        mainWindow.hide();
      } else {
        mainWindow.show();
        mainWindow.focus();
      }
    }
  });

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

// 当所有窗口都关闭时退出应用
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// 应用退出前的清理
app.on('before-quit', () => {
  isQuitting = true;
  globalShortcut.unregisterAll();
});

// IPC 通信处理 - 流式消息
ipcMain.handle('send-message-stream', async (event, message) => {
  try {
    const axios = require('axios');
    
    // 发送流式请求
    try {
      const requestData = {
        inputs: {},
        query: message,
        response_mode: 'streaming',
        conversation_id: store.get('conversationId', ''),
        user: config.api.user
      };
      
      const requestBody = JSON.stringify(requestData);
      
      const response = await axios.post(apiConfig.url, requestBody, {
        headers: {
          'Authorization': `Bearer ${apiConfig.key}`,
          'Content-Type': 'application/json',
          'Content-Length': Buffer.byteLength(requestBody, 'utf8'),
          'Accept': 'text/event-stream',
          'Cache-Control': 'no-cache',
          'Connection': 'keep-alive'
        },
        timeout: config.api.timeout,
        responseType: 'stream',
        proxy: false,
        httpsAgent: null,
        validateStatus: function (status) {
          return status >= 200 && status < 500;
        }
      });

      // 处理流式响应
      let fullAnswer = '';
      let conversationId = '';
      
      response.data.on('data', (chunk) => {
        const lines = chunk.toString().split('\n');
        
        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const rawData = line.slice(6).trim();
            if (rawData === '[DONE]') {
              console.log('流式响应完成');
              event.sender.send('stream-complete', {
                fullAnswer,
                conversation_id: conversationId
              });
              return;
            }
            
            if (rawData === '' || rawData === '{}') {
              continue; // 跳过空数据
            }
            
            try {
              const data = JSON.parse(rawData);
              
              if (data.event === 'message') {
                fullAnswer += data.answer || '';
                // 发送增量更新到渲染进程
                event.sender.send('stream-chunk', {
                  chunk: data.answer || '',
                  fullText: fullAnswer
                });
              } else if (data.event === 'message_end') {
                conversationId = data.conversation_id || '';
                // 保存会话ID
                if (conversationId) {
                  store.set('conversationId', conversationId);
                }
                // 发送完成信号
                event.sender.send('stream-complete', {
                  fullAnswer,
                  conversation_id: conversationId
                });
              }
            } catch (parseError) {
              console.log('解析流数据失败:', parseError.message, '原始数据:', rawData.substring(0, 100));
              // 尝试修复常见的Unicode转义问题
              try {
                const fixedData = rawData.replace(/\\u([0-9a-fA-F]{4})/g, (match, code) => {
                  return String.fromCharCode(parseInt(code, 16));
                });
                const data = JSON.parse(fixedData);
                if (data.event === 'message') {
                  fullAnswer += data.answer || '';
                  event.sender.send('stream-chunk', {
                    chunk: data.answer || '',
                    fullText: fullAnswer
                  });
                }
              } catch (fixError) {
                console.error('修复后仍解析失败:', fixError.message);
              }
            }
          }
        }
      });

      response.data.on('end', () => {
        console.log('流式响应结束');
      });

      response.data.on('error', (streamError) => {
        console.error('流式响应错误:', streamError);
        event.sender.send('stream-error', {
          error: streamError.message
        });
      });

      return {
        success: true,
        streaming: true
      };
      
    } catch (apiError) {
      console.error('API连接失败，详细错误:', apiError.message);
      let errorMessage = apiError.message;
      
      if (apiError.code === 'ECONNREFUSED') {
        errorMessage = 'ECONNREFUSED: 无法连接到API服务器，请确保服务器正在运行';
      } else if (apiError.code === 'ETIMEDOUT' || apiError.message.includes('timeout')) {
        errorMessage = 'TIMEOUT: 连接超时，请检查网络状态或增加超时时间';
      } else if (apiError.response) {
        if (apiError.response.status === 404) {
          errorMessage = '404错误：API接口地址不存在，请检查配置是否正确';
        } else {
          errorMessage = `请求失败，状态码: ${apiError.response.status}\n错误内容: ${JSON.stringify(apiError.response.data)}`;
        }
      }
      
      return {
        success: false,
        error: errorMessage
      };
    }
  } catch (error) {
    console.error('处理消息失败:', error);
    return {
      success: false,
      error: error.message
    };
  }
});

// 保持原有的阻塞式API作为备用
ipcMain.handle('send-message', async (event, message) => {
  try {
    const axios = require('axios');
    
    // 首先尝试连接实际API
    try {
      const requestData = {
        inputs: {},
        query: message,
        response_mode: 'blocking',
        conversation_id: store.get('conversationId', ''),
        user: config.api.user
      };
      
      const requestBody = JSON.stringify(requestData);
      
      const response = await axios.post(apiConfig.url, requestBody, {
        headers: {
          'Authorization': `Bearer ${apiConfig.key}`,
          'Content-Type': 'application/json',
          'Content-Length': Buffer.byteLength(requestBody, 'utf8'),
          'Accept': 'application/json',
          'User-Agent': 'AI-Floating-Assistant/1.0'
        },
        timeout: config.api.timeout,
        proxy: false,  // 禁用系统代理
        httpsAgent: null,  // 禁用HTTPS代理
        validateStatus: function (status) {
          return status >= 200 && status < 500; // 接受所有非500错误的响应
        }
      });

      // 保存会话ID
      if (response.data.conversation_id) {
        store.set('conversationId', response.data.conversation_id);
      }

      return {
        success: true,
        data: {
          answer: response.data.answer || '[无回答]',
          conversation_id: response.data.conversation_id
        }
      };
    } catch (apiError) {
      console.error('API连接失败，详细错误:', apiError.message);
      let errorMessage = apiError.message;
      
      if (apiError.code === 'ECONNREFUSED') {
        errorMessage = 'ECONNREFUSED: 无法连接到API服务器，请确保服务器正在运行';
      } else if (apiError.code === 'ETIMEDOUT' || apiError.message.includes('timeout')) {
        errorMessage = 'TIMEOUT: 连接超时，请检查网络状态或增加超时时间';
      } else if (apiError.response) {
        if (apiError.response.status === 404) {
          errorMessage = '404错误：API接口地址不存在，请检查配置是否正确';
        } else {
          errorMessage = `请求失败，状态码: ${apiError.response.status}\n错误内容: ${JSON.stringify(apiError.response.data)}`;
        }
      }
      
      return {
        success: false,
        error: errorMessage
      };
    }
  } catch (error) {
    console.error('处理消息失败:', error);
    return {
      success: false,
      error: error.message
    };
  }
});

// 窗口控制
ipcMain.handle('minimize-window', () => {
  if (mainWindow) {
    mainWindow.hide();
  }
});

ipcMain.handle('close-app', () => {
  isQuitting = true;
  app.quit();
});

// 调整窗口大小
ipcMain.handle('resize-window', (event, width, height) => {
  if (mainWindow) {
    const currentBounds = mainWindow.getBounds();
    const currentHeight = currentBounds.height;
    
    // 计算新位置以保持底部固定
    const newY = currentBounds.y + (currentHeight - height);
    
    console.log('当前边界:', currentBounds, '目标大小:', width, height, '新Y:', newY);
    
    // 设置新大小和位置
    mainWindow.setBounds({
      x: currentBounds.x,
      y: newY,
      width: width,
      height: height
    }, true); // animate
    
    // 确保窗口内容重新布局
    setTimeout(() => {
      mainWindow.webContents.executeJavaScript(`
        window.dispatchEvent(new Event('resize'));
      `);
    }, 100);
  }
});